#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import hashlib
from flask import url_for, request

from spider.lib.escape import to_unicode
from spider.lib.utils import safe_int, sub_string_by_length


def register_routes(app):
    from spider.views.api import register_api
    register_api(app, url_prefix='/')
    return app


def register_resources(app):
    if not hasattr(app, '_static_hash'):
        app._static_hash = {}

    def static_file(filename):
        c = app.config
        prefix = c.get('SITE_STATIC_PREFIX', '/static/')
        if filename in app._static_hash:
            return app._static_hash[filename]
        try:
            with open(os.path.join(app.static_folder, filename), 'r') as f:
                content = f.read()
                hsh = hashlib.md5(content).hexdigest()
            value = '%s%s?v=%s' % (prefix, filename, hsh[:5])
        except:
            value = '%s%s' % (prefix, filename)
        app._static_hash[filename] = value
        return value

    def url_for_page(page):
        args = dict(request.args.copy())
        args['page'] = page
        args.update(request.view_args)
        return url_for(request.endpoint, **args)

    def url_for_args(**kwargs):
        args = request.args.copy()
        for k, v in kwargs.iteritems():
            args[k] = v
        return url_for(request.endpoint, **args)

    @app.context_processor
    def register_context():
        return dict(
            static_file=static_file,
            url_for_args=url_for_args,
            to_unicode=to_unicode
        )
    app.jinja_env.globals['url_for_page'] = url_for_page
    app.jinja_env.globals['int'] = safe_int
    app.jinja_env.globals['for_with_index'] = enumerate
    app.jinja_env.globals['len'] = len
    app.jinja_env.globals['sub_string_by_length'] = sub_string_by_length


def register_error_handlers(app):
    pass
